# coding=utf-8
import json
import logging
import time
from django.db import transaction

from worldcup.apps.userModel.models import User, TravelEvent, Travel, Comment, Advice
from worldcup.commons.CommonResult import rest, CommonResult

logger = logging.getLogger('django')
@rest
def get_user(request):
    openid = request.GET["openid"]
    user = User.objects.filter(openid=openid).get()
    return CommonResult(0, {
        "openid": user.openid,
        "wxname": user.wxname,
        "gender": user.gender,
        "imgurl": user.imgurl,
        "age": user.age,
        "wxid": user.wxid,
        "description": user.description
    })


@rest
def get_remind_survey(request):
    openid = request.GET["openid"]
    top_events = TravelEvent.objects.values("status").filter(rec_openid=openid, event=1).all();
    topNotViewNum = 0
    for top_event in top_events:
        if top_event['status'] == 1:
            topNotViewNum += 1
    view_events = TravelEvent.objects.values("status").filter(rec_openid=openid, event=2).all()
    viewNotViewNum = 0
    for view_event in view_events:
        if view_event['status'] == 1:
            viewNotViewNum += 1
    dates = TravelEvent.objects.values("status").filter(rec_openid=openid, event=3).all()
    dateNotViewNum = 0
    for date in dates:
        if date["status"] == 1:
            dateNotViewNum += 1
    date_results = TravelEvent.objects.values("status").filter(openid=openid, event=3).all()
    dateResultNotViewNum = 0
    for date_result in date_results:
        if date_result["status"] == 1:
            dateResultNotViewNum += 1
    # comment
    commentNotViewNum = Comment.objects.filter(messaged_openid=openid, status=1).count()
    return CommonResult(0, {
        "topNum": len(top_events),
        "topNotViewNum": topNotViewNum,
        "viewNum": len(view_events),
        "viewNotViewNum": viewNotViewNum,
        "dateNum": len(dates),
        "dateNotViewNum": dateNotViewNum,
        "dateResultNum": len(date_results),
        "dateResultNotViewNum": dateResultNotViewNum,
        "commentNotViewNum": commentNotViewNum,
    })


@transaction.atomic
@rest
def get_remind_top(request):
    try:
        openid = request.GET["openid"]
        size = int(request.GET.get("size"))
        page = int(request.GET.get("page"))
    except KeyError:
        page = 1
        size = 20
    except TypeError:
        page = 1
        size = 20
    # 顶
    top = {"users": []}
    top_events = TravelEvent.objects.filter(rec_openid=openid, event=1).order_by("-created_at").all()[
                 (page - 1) * size: page * size]
    topNotViewNum = 0
    for top_event in top_events:
        if top_event.status == 1:
            topNotViewNum += 1
            top_event.status = 2
            top_event.save()
        user = User.objects.filter(openid=top_event.openid).get()
        travel = Travel.objects.filter(openid=openid, travel_type=1).get()

        # isApply 今天是否已经看过此人
        view_count = TravelEvent.objects.values("openid").filter(openid=openid, rec_openid=user.openid, event=2,
                        created_at__gte=int(time.mktime(time.strptime(time.strftime('%Y-%m-%d 00:00:00',
                        time.localtime(time.time())),'%Y-%m-%d %H:%M:%S')))).distinct().count()
        is_apply = 1 if view_count > 0 else 0

        # isUp 今天是否点赞过此人
        up_count = TravelEvent.objects.values("openid").filter(openid=openid, rec_openid=user.openid, event=1,
                        created_at__gte=int(time.mktime(time.strptime(time.strftime('%Y-%m-%d 00:00:00',
                        time.localtime(time.time())),'%Y-%m-%d %H:%M:%S')))).distinct().count()
        is_up = 1 if up_count > 0 else 0

        top['users'].append({
            "openid": user.openid,
            "name": user.name,
            "gender": user.gender,
            "age": user.age,
            "supportTeams": user.support_teams,
            "peerNum": travel.peer_num,
            "imgUrl": user.imgurl,
            "createdAt": top_event.created_at,
            "isApply":is_apply,
            "isUp": is_up,
        })
    top["topNum"] = len(top_events)
    top["topNotViewNum"] = topNotViewNum
    return CommonResult(0, {
        "top": top,
    })


@transaction.atomic
@rest
def get_remind_view(request):
    try:
        openid = request.GET["openid"]
        size = int(request.GET.get("size"))
        page = int(request.GET.get("page"))
    except KeyError:
        page = 1
        size = 20
    except TypeError:
        page = 1
        size = 20
    view = {'users': []}
    view_events = TravelEvent.objects.filter(rec_openid=openid, event=2).order_by("-created_at").all()[
                  (page - 1) * size: page * size]
    viewNotViewNum = 0
    for view_event in view_events:
        if view_event.status == 1:
            viewNotViewNum += 1
            # 更改状态
            view_event.status = 2
            view_event.save()
        user = User.objects.filter(openid=view_event.openid).get()
        travel = Travel.objects.filter(openid=openid, travel_type=1).get()

        # isApply 今天是否已经看过此人
        view_count = TravelEvent.objects.values("openid").filter(openid=openid, rec_openid=user.openid, event=2,
                                                                 created_at__gte=int(time.mktime(
                                                                     time.strptime(time.strftime('%Y-%m-%d 00:00:00',
                                                                                                 time.localtime(
                                                                                                     time.time())),
                                                                                   '%Y-%m-%d %H:%M:%S')))).distinct().count()
        is_apply = 1 if view_count > 0 else 0

        # isUp 今天是否点赞过此人
        up_count = TravelEvent.objects.values("openid").filter(openid=openid, rec_openid=user.openid, event=1,
                                                               created_at__gte=int(time.mktime(
                                                                   time.strptime(time.strftime('%Y-%m-%d 00:00:00',
                                                                                               time.localtime(
                                                                                                   time.time())),
                                                                                 '%Y-%m-%d %H:%M:%S')))).distinct().count()
        is_up = 1 if up_count > 0 else 0
        view['users'].append({
            "openid": user.openid,
            "name": user.name,
            "gender": user.gender,
            "age": user.age,
            "supportTeams": user.support_teams,
            "peerNum": travel.peer_num,
            "imgUrl": user.imgurl,
            "createdAt": view_event.created_at,
            "isApply": is_apply,
            "isUp": is_up,
        })
    view['viewNum'] = len(view_events)
    view['viewNotViewNum'] = viewNotViewNum
    return CommonResult(0, {
        "view": view,
    })


@transaction.atomic
@rest
def get_remind_dates(request):
    try:
        openid = request.GET["openid"]
        size = int(request.GET.get("size"))
        page = int(request.GET.get("page"))
    except KeyError:
        page = 1
        size = 20
    except TypeError:
        page = 1
        size = 20
    dates = {'users': []}
    date_events = TravelEvent.objects.filter(rec_openid=openid, event=3).order_by("-created_at").all()[
                  (page - 1) * size: page * size]
    for date_event in date_events:
        if date_event.status == 1:
            date_event.status = 2
            date_event.save()
        user = User.objects.filter(openid=date_event.openid).get()
        # isApply 今天是否已经看过此人
        view_count = TravelEvent.objects.values("openid").filter(openid=openid, rec_openid=user.openid, event=2,
                                                                 created_at__gte=int(time.mktime(
                                                                     time.strptime(time.strftime('%Y-%m-%d 00:00:00',
                                                                                                 time.localtime(
                                                                                                     time.time())),
                                                                                   '%Y-%m-%d %H:%M:%S')))).distinct().count()
        is_apply = 1 if view_count > 0 else 0

        # isUp 今天是否点赞过此人
        up_count = TravelEvent.objects.values("openid").filter(openid=openid, rec_openid=user.openid, event=1,
                                                               created_at__gte=int(time.mktime(
                                                                   time.strptime(time.strftime('%Y-%m-%d 00:00:00',
                                                                                               time.localtime(
                                                                                                   time.time())),
                                                                                 '%Y-%m-%d %H:%M:%S')))).distinct().count()
        is_up = 1 if up_count > 0 else 0
        dates['users'].append({
            "dateId": date_event.id,
            "openid": user.openid,
            "name": user.name,
            "result": date_event.result,
            "imgUrl": user.imgurl,
            "createdAt": date_event.created_at,
            "isApply": is_apply,
            "isUp": is_up,
        })
    return CommonResult(0, {
        "dates": dates,
    })


@transaction.atomic
@rest
def get_remind_results(request):
    try:
        openid = request.GET["openid"]
        size = int(request.GET.get("size"))
        page = int(request.GET.get("page"))
    except KeyError:
        page = 1
        size = 20
    except TypeError:
        page = 1
        size = 20
    # 结果
    results = {'users': []}
    result_events = TravelEvent.objects.filter(openid=openid, event=3).order_by("-created_at").all()[
                    (page - 1) * size: page * size]
    for result_event in result_events:
        if result_event.status == 1:
            result_event.status = 2
            result_event.save()
        user = User.objects.filter(openid=result_event.rec_openid).get()
        # isApply 今天是否已经看过此人
        view_count = TravelEvent.objects.values("openid").filter(openid=openid, rec_openid=user.openid, event=2,
                                                                 created_at__gte=int(time.mktime(
                                                                     time.strptime(time.strftime('%Y-%m-%d 00:00:00',
                                                                                                 time.localtime(
                                                                                                     time.time())),
                                                                                   '%Y-%m-%d %H:%M:%S')))).distinct().count()
        is_apply = 1 if view_count > 0 else 0

        # isUp 今天是否点赞过此人
        up_count = TravelEvent.objects.values("openid").filter(openid=openid, rec_openid=user.openid, event=1,
                                                               created_at__gte=int(time.mktime(
                                                                   time.strptime(time.strftime('%Y-%m-%d 00:00:00',
                                                                                               time.localtime(
                                                                                                   time.time())),
                                                                                 '%Y-%m-%d %H:%M:%S')))).distinct().count()
        is_up = 1 if up_count > 0 else 0
        results['users'].append({
            "openid": user.openid,
            "name": user.name,
            "imgUrl": user.imgurl,
            "createdAt": result_event.created_at,
            "result": result_event.result,
            "isApply": is_apply,
            "isUp": is_up,
        })
    return CommonResult(0, {
        "results": results,
    })


@rest
def get_remind(request):
    openid = request.GET["openid"]
    # 顶
    top = {"users": []}
    top_events = TravelEvent.objects.filter(rec_openid=openid, event=1).all()
    topNotViewNum = 0
    for top_event in top_events:
        if top_event.status == 1:
            topNotViewNum += 1
        user = User.objects.filter(openid=top_event.openid).get()
        travel = Travel.objects.filter(openid=openid, travel_type=1).get()
        top['users'].append({
            "openid": user.openid,
            "name": user.name,
            "gender": user.gender,
            "age": user.age,
            "supportTeams": user.support_teams,
            "peerNum": travel.peer_num,
            "imgUrl": user.imgurl,
            "createdAt": top_event.created_at,
        })
    top["topNum"] = len(top_events)
    top["topNotViewNum"] = topNotViewNum

    # 查看
    view = {'users': []}
    view_events = TravelEvent.objects.filter(rec_openid=openid, event=2).all()
    viewNotViewNum = 0
    for view_event in view_events:
        if view_event.status == 1:
            viewNotViewNum += 1
        user = User.objects.filter(openid=view_event.openid).get()
        travel = Travel.objects.filter(openid=openid, travel_type=1).get()
        view['users'].append({
            "openid": user.openid,
            "name": user.name,
            "gender": user.gender,
            "age": user.age,
            "supportTeams": user.support_teams,
            "peerNum": travel.peer_num,
            "imgUrl": user.imgurl,
            "createdAt": view_event.created_at,
        })
    view['viewNum'] = len(view_events)
    view['viewNotViewNum'] = viewNotViewNum

    # 约伴
    dates = {'users': []}
    date_events = TravelEvent.objects.filter(rec_openid=openid, event=3, result=3).all()
    for date_event in date_events:
        user = User.objects.filter(openid=date_event.openid).get()
        dates['users'].append({
            "dateId": date_event.id,
            "openid": user.openid,
            "name": user.name,
            "imgUrl": user.imgurl,
            "createdAt": date_event.created_at,
        })
    # 结果
    results = {'users': []}
    result_events = TravelEvent.objects.filter(openid=openid, event=3).all()
    for result_event in result_events:
        user = User.objects.filter(openid=result_event.openid).get()
        results['users'].append({
            "openid": user.openid,
            "name": user.name,
            "imgUrl": user.imgurl,
            "createdAt": result_event.created_at,
            "result": result_event.result
        })

    # 评论
    comments = []

    return CommonResult(0, {
        "top": top,
        "view": view,
        "dates": dates,
        "results": results,
        # "comments": comments
    })


@rest
def get_address(request):
    openid = request.GET.get("openid")
    if openid is None or openid == "":
        return CommonResult(-1, "openid不能为空")
    user = User.objects.values("address_info").filter(openid=openid).get()
    return CommonResult(1, {"addressInfo": user["address_info"]})


@rest
def update_address(request):
    request_params = json.loads(request.body)
    openid = request_params["openid"]
    address_info = request_params["addressInfo"]
    logger.info("update addressInfo , openid = " + openid + " , address_info = " + address_info)
    user = User.objects.filter(openid=openid).get()
    user.address_info = address_info
    user.save()
    return CommonResult(0, "success")

@rest
def add_advice(request):
    adviceStr = request.POST.get("advice")
    openid = request.POST.get("openid")
    advice = Advice()
    advice.openid = openid
    advice.advice = adviceStr
    advice.save()
    return CommonResult(0, "success")
